package org.example.onlinechat.controller;

import org.example.onlinechat.common.Result;
import org.example.onlinechat.entity.User;
import org.example.onlinechat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:7070")
@RestController
@RequestMapping("/User")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login (@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        List<User> user = userService.findByUsername(username);
        System.out.println(user);
        User user1 = user.get(0);

        if (user != null && user1.getPassword().equals(password)&&user1.getUsername().equals(username)) {
            // 登录成功，返回用户信息
            Map<String, Object> data = new HashMap<>();
            data.put("user_id", user1.getUser_id());
            data.put("username", user1.getUsername());
            return Result.success(data);
        } else {
            // 登录失败，返回错误信息
            return Result.error("401", "用户名或密码错误");
        }
    }

    @PostMapping("/Reg")
    public Result register(@RequestBody User user) {
        String name =user.getUsername();
        List<User> list =userService.findFromUsername(name);
        if (!list.isEmpty()){
            return Result.error("账号已存在");
        }else {
            userService.register(user);
        }
        return Result.success();
    }

}
